<?php defined('SYSPATH') OR die('No direct access allowed.');

require_once "gapi/src/apiClient.php";
require_once "gapi/src/contrib/apiLatitudeService.php";



class Welcome_Controller extends Controller {

	// Set the name of the template to use
	//public $template = 'template';
	private $access_model;

	public function __construct() {
		parent::__construct();
		$this->access_model = new Accesstoken_Model();
	}

	public function index()
	{
	    $this->template = new View('template');
		$this->template->content = new View('welcome_content');
		$this->template->title = 'Bus Tracker';
		$this->template->content->links = array
		(
			'Home Page'     => 'http://kohanaphp.com/',
			'Documentation' => 'http://docs.kohanaphp.com/',
			'Forum'         => 'http://forum.kohanaphp.com/',
			'License'       => 'Kohana License.html',
			'Donate'        => 'http://kohanaphp.com/donate',
		);
		$this->template->render(TRUE);
	}

	public function selectBus($source, $destination) {
	  
	    $redbus = new Redbus_Model();
	    $buses = $redbus->getBusesAvailableTodayCompact($source, $destination);	    
        $selectbus = new View('selectbus');
        $selectbus->buses = $buses;
        $selectbus->render(TRUE);	
	}
	
	public function track($id=100, $isRender=1) {
		$token = $this->access_model->getToken($id);
		$content = new View('track');
		if(!empty($token)) {
			$apiClient = new apiClient();
			$latitude = new apiLatitudeService($apiClient);
			$apiClient->setAccessToken($token->token);
			$response = $latitude->getCurrentLocation();
			$now = time();
			$response2 = $latitude->listLocation($now*1000, ($now-20*86400)*1000, 1000, 'best');
			
			$content->name = $token->name;
			$content->latitude = $response['latitude'];
			$content->longitude= $response['longitude'];
			$content->history = $response2;
		} else {
			$content->name ="None";
			$content->latitude = 1;
			$content->longitude= 1;
			$content->history = array();		  
		}
		
		if ($isRender == 1)
		  $content->render(TRUE);
		else {
		  echo json_encode($response);
		}
	}
	
	//Might be redundant function.
//	public function getPositionCoords($id=100) {
//		$token = $this->access_model->getToken($id);
//		if(!empty($token)) {
//			$apiClient = new apiClient();
//			$latitude = new apiLatitudeService($apiClient);
//			$apiClient->setAccessToken($token->token);
//			$response = $latitude->getCurrentLocation();
//
//			$name = $token->name;
//			$newlatitude = $response['latitude'];
//			$newlongitude= $response['longitude'];
//		} else {
//			$name ="None";
//			$newlatitude = 1;
//			$newlongitude= 1;		  
//		}
//	}


} // End Welcome Controller
